﻿using CsvHelper;
using CsvHelper.Configuration;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataCapture.Helper;

namespace DataCapture.Helper
{
    public class AddressConfigReader
    {

        private readonly  List<string> ActionfilePaths = new List<string> {
            "Action_RXJ.csv", "Action_XCCLJ.csv", "Action_ZJFFJ.csv","Action_JSZSJ.csv",
            "Action_XPMJJ.csv", "Action_JCGSLJ.csv","Action_KKJ.csv", "Action_ZDZDJ.csv",
            "Report.csv"};

        private readonly List<string> AlarmfilePaths = new List<string> {
            "Alarm_RXJ.csv","Alarm_XCCLJ.csv","Alarm_ZJFFJ.csv","Alarm_JSZSJ.csv",
            "Alarm_XXBPJCJ.csv","Alarm_RGPMJ.csv","Alarm_XPMJJ.csv","Alarm_JGJC.csv",
            "Alarm_LMTSJ.csv","Alarm_KKJ.csv","Alarm_ZDTBJ.csv","Alarm_JGDMZSGJ.csv",
            "Alarm_ZDZDJ.csv","Alarm_ZXTBJ.csv",};


        /// <summary>
        /// 读取csv文件列表
        /// </summary>
        /// <param name="filePaths"></param>
        /// <returns></returns>
        public void ReadConfigsFromMultipleFiles()
        {
            try
            {
                PublicHelp.ActionAddressConfigs.Clear();
                //将Action所有csv文件读取
                int key = (int)PublicHelp.deviceType.RXJ;
                foreach (string filePath in ActionfilePaths)
                {
                    List<PublicHelp.ActionAddressConfig> currentConfigs = ActionReadConfigs(filePath);

                    //每一个csv文件配置对应一个key，保存在全局变量AddressConfigs中
                    PublicHelp.ActionAddressConfigs[key] = currentConfigs;
                    key++;
                }
                if (MainForm.Instance != null)
                {
                    Log4NetHelper.Debug($"ActionAddressTable数据反序列化完成。",true);
                }

                PublicHelp.AlarmAddressConfigs.Clear();
                //将Alarm所有csv文件读取
                key = (int)PublicHelp.deviceType.RXJ;
                foreach (string filePath in AlarmfilePaths)
                {
                    List<PublicHelp.AlarmAddressConfig> currentConfigs = AlarmReadConfigs(filePath);

                    //每一个csv文件配置对应一个key，保存在全局变量AddressConfigs中
                    PublicHelp.AlarmAddressConfigs[key] = currentConfigs;
                    key++;
                }
                if (MainForm.Instance != null)
                {
                    Log4NetHelper.Debug($"AlarmAddressTable数据反序列化完成。",true);
                }
            }
            catch(Exception ex)
            {

                if (MainForm.Instance != null)
                {
                    Log4NetHelper.Debug($"AddressTable数据反序列化失败,{ex.Message}",true);
                }
            }
        }

        /// <summary>
        /// 读取单个Actioncsv文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static List<PublicHelp.ActionAddressConfig> ActionReadConfigs(string filePath)
        {
            List<PublicHelp.ActionAddressConfig> configs = new List<PublicHelp.ActionAddressConfig>();

            //var csvConfig = new CsvConfiguration(CultureInfo.InvariantCulture)
            //{
            //    HasHeaderRecord = true, // 设置CSV文件包含表头  
            //};

            try
            {
                using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                using (var reader = new StreamReader(stream))
                using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                {
                    csv.Read();       // 跳过表头  
                    csv.ReadHeader(); // 或者使用HasHeader来指定是否有表头  

                    while (csv.Read())
                    {
                        var record = new PublicHelp.ActionAddressConfig
                        {
                            Address = csv.GetField<string>("Address"),
                            Length = csv.GetField<ushort>("Length"),
                            AddressType = (PublicHelp.AddressType)Enum.Parse(typeof(PublicHelp.AddressType), csv.GetField<string>("AddressType"), true)
                            // 注意：如果AddressType是字符串而不是枚举值，则直接使用 GetField<string>("AddressType")  
                        };
                        configs.Add(record);
                    }
                }
            }
            catch (FileNotFoundException ex)
            {
                // 处理文件未找到异常  
                Console.WriteLine("文件未找到: " + ex.Message);
            }
            catch (IOException ex)
            {
                // 处理I/O异常，比如文件读取错误  
                Console.WriteLine("I/O错误: " + ex.Message);
            }
            catch (CsvHelper.HeaderValidationException ex)
            {
                // 处理CSV头部验证异常，比如列名不匹配  
                Console.WriteLine("CSV头部验证错误: " + ex.Message);
            }
            catch (CsvHelper.BadDataException ex)
            {
                // 处理CSV数据格式错误，比如类型不匹配  
                Console.WriteLine("CSV数据格式错误: " + ex.Message);
            }
            catch (Exception ex)
            {
                // 处理其他未预期的异常  
                Console.WriteLine("发生未知错误: " + ex.Message);
                // 可能需要在这里返回null或抛出一个自定义异常  
            }
            return configs;
            
        }

        /// <summary>
        /// 读取单个Actioncsv文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static List<PublicHelp.AlarmAddressConfig> AlarmReadConfigs(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                return null;
            }
            List<PublicHelp.AlarmAddressConfig> configs = new List<PublicHelp.AlarmAddressConfig>();

            try
            {
                filePath = $"AddressTable/{filePath}";
                using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                //using (var reader = new StreamReader(stream, Encoding.GetEncoding("GBK")))
                using (var reader = new StreamReader(stream, Encoding.UTF8))
                using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                {
                    csv.Read();       // 跳过表头  
                    csv.ReadHeader(); // 或者使用HasHeader来指定是否有表头  

                    while (csv.Read())
                    {
                        var record = new PublicHelp.AlarmAddressConfig
                        {
                            alarmId = csv.GetField<string>("Address"),
                            alarmContan = csv.GetField<string>("Content"),
                            addressType = csv.GetField<string>("AddressType"),
                            trigger = csv.GetField<string>("Trigger")
                        };
                        configs.Add(record);
                    }
                }
            }
            catch (FileNotFoundException ex)
            {
                // 处理文件未找到异常  
                Console.WriteLine("文件未找到: " + ex.Message);
            }
            catch (IOException ex)
            {
                // 处理I/O异常，比如文件读取错误  
                Console.WriteLine("I/O错误: " + ex.Message);
            }
            catch (CsvHelper.HeaderValidationException ex)
            {
                // 处理CSV头部验证异常，比如列名不匹配  
                Console.WriteLine("CSV头部验证错误: " + ex.Message);
            }
            catch (CsvHelper.BadDataException ex)
            {
                // 处理CSV数据格式错误，比如类型不匹配  
                Console.WriteLine("CSV数据格式错误: " + ex.Message);
            }
            catch (Exception ex)
            {
                // 处理其他未预期的异常  
                Console.WriteLine("发生未知错误: " + ex.Message);
                // 可能需要在这里返回null或抛出一个自定义异常  
            }
            return configs;

        }
    }
}

